<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue';
import { onMounted, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';
import { cloneDeep } from 'lodash-es';
import { useFallBack } from '../useFallBack';
import { useImgEventStore } from '@/store/modules/dcp/image_management/imgEvent';
// 返回
const props = defineProps({
  getImgDetails: {
    type: Function as PropType<() => void>,
    required: true,
  },
  event: {
    type: String as PropType<string>,
    required: true,
  },
});
// 数据处理
const loading = ref<boolean>(false);
const data = ref<DetailsItem[]>([]);
const editableData: UnwrapRef<Record<string, any>> = reactive({});
const searchKeyword = ref<string>('');
const total = ref<number>(0);
const pageSize = ref<number>(10);
const current = ref<number>(1);
const columns: any = [
  {
    title: '部门',
    dataIndex: 'department',
    key: 'department',
    width: '5%',
    align: 'center',
  },
  {
    title: '主要人员',
    dataIndex: 'mainPersonnel',
    key: 'mainPersonnel',
    width: '10%',
    align: 'center',
  },
  {
    title: '事件名称',
    dataIndex: 'eventName',
    key: 'eventName',
    width: '10%',
    align: 'center',
  },
  {
    title: '活动时间',
    dataIndex: 'eventTime',
    key: 'eventTime',
    width: '10%',
    align: 'center',
  },
  {
    title: '活动地点',
    dataIndex: 'eventLocation',
    key: 'eventLocation',
    width: '15%',
    align: 'center',
  },
  {
    title: '标签',
    dataIndex: 'tags',
    key: 'tags',
    width: '10%',
    align: 'center',
  },
  {
    title: '下载次数',
    dataIndex: 'downloadCount',
    key: 'downloadCount',
    width: '5%',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '10%',
    align: 'center',
    fixed: 'right',
  },
];

// 接口
interface DetailsItem {
  id: number
  department: string
  mainPersonnel: string
  eventName: string
  eventTime: string
  eventLocation: string
  tags: string
  downloadCount: number
  link: string
}

// 获取所有图片或视频数据
async function fetchData() {
  data.value = [];
  loading.value = true;
  if (props.event === '无分配文件夹的文件') {
    await getImgByEventPage('', current.value, pageSize.value).then((res: any) => {
      total.value = res.total;
      data.value = res.data.records;
    }).catch(() => {
      message.error('获取数据失败！');
    }).finally(() => {
      loading.value = false;
    });
  }
  else {
    await getImgByEventPage(props.event, current.value, pageSize.value).then((res: any) => {
      total.value = res.total;
      data.value = res.data.records;
    }).catch(() => {
      message.error('获取数据失败！');
    }).finally(() => {
      loading.value = false;
    });
  }
}
async function handleTableChange(pagination: any) {
  pageSize.value = pagination.pageSize;
  current.value = pagination.current;
  if (searchKeyword.value === '') {
    fetchData();
  }
}
async function onSearch(searchKeyword: string) {
  // 输入校验
  if (!searchKeyword || searchKeyword.trim() === '') {
    message.error('搜索关键词不能为空');
    return;
  }
  await searchpicture(searchKeyword).then((response: any) => {
    // 检查响应数据
    if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
      if (props.event === '无分配文件夹的文件') {
        data.value = response.data.filter((event: any) => event.event === null || event.event === '');
      }
      else {
        data.value = response.data.filter((event: any) => event.event === props.event);
      }
      message.success('搜索成功');
    }
    else {
      // 如果没有有效的数据
      message.error('没有找到匹配的数据');
    }
  });
}
onMounted(() => {
  fetchData();
});

// 删除记录
async function onDelete(record: any) {
  // const flag = ref<boolean>(false)
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== record.id);
      deleteSingleRecord(record);
    },
  });
}
function extractAfterSxint(path: string): string | null {
  const parts = path.split('/sxint/');
  if (parts.length > 1) {
    return parts[1];
  }
  return null;
}
async function deleteSingleRecord(record: any) {
  // 获取图片的link
  const keys = [extractAfterSxint(record.link)];

  // 删除图片
  await deleteFiles({ namespace: 'sxint', keys }).then(() => {
    message.success('删除成功');
  });
  // 删除记录
  await picturedeleteids([record.id]).then(() => {
    message.success('记录删除成功！');
    fetchData();
  }).catch(() => {
    message.error('记录删除失败！');
  });
}

// 编辑记录
function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  const updateDate = {
    id: newData.id,
    department: newData.department,
    mainPersonnel: newData.mainPersonnel,
    eventName: newData.eventName,
    eventTime: newData.eventTime,
    eventLocation: newData.eventLocation,
    tags: newData.tags,
    downloadCount: newData.downloadCount,
    link: newData.link,
  };
  await updatepicture(updateDate).then(() => {
    message.success('修改成功');
  });
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

// 预览
const visibleImg = ref<boolean>(false);
const imgItem = ref<any>();
function showModalImg(record: any) {
  imgItem.value = record;
  visibleImg.value = true;
}

// 判断是否为视频
function isMp4(link: any) {
  return link.toLowerCase().endsWith('.mp4');
}

// 移动文件夹
const value1 = ref<string>('');
const options = ref<any[]>([]);
const record = ref<any>([]);
const visibleFile = ref<boolean>(false);
function moveFile(r: any) {
  value1.value = '';
  record.value = [];
  record.value = r;
  visibleFile.value = !visibleFile.value;
}
async function handleOk() {
  // 修改event
  const updateDate = {
    id: record.value.id,
    department: record.value.department,
    mainPersonnel: record.value.mainPersonnel,
    eventName: record.value.eventName,
    eventTime: record.value.eventTime,
    eventLocation: record.value.eventLocation,
    tags: record.value.tags,
    downloadCount: record.value.downloadCount,
    link: record.value.link,
    event: value1.value,
    eventType: record.value.eventType,
  };
  await updatepicture(updateDate).then(() => {
    message.success('修改成功');
    fetchData();
  });
  visibleFile.value = false;
}
const choose = ref('1');
function ischoose1() {
  return choose.value === '1';
}
async function getOptions(eventList: any) {
  for (let i = 0; i < eventList.length; i++) {
    options.value.push({ value: eventList[i] });
  }
}
onMounted(async () => {
  await useImgEventStore().getEventList();
  getOptions(useImgEventStore().eventList);
});
</script>

<template>
  <div>
    <div class="header">
      <div class="left">
        <a-space>
          <p>文件夹：{{ props.event }}</p>
          <a-input-search
            v-model="searchKeyword" v-auth="'e-details-search'" placeholder="请输入关键字" enter-button
            style="width: 15vw;" @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-button type="primary" @click="props.getImgDetails()">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <a-table
      :columns="columns" :data-source="data" row-key="id" class="d-table" :scroll="{ x: 2000 }"
      :loading="loading" :pagination="{ pageSize, showQuickJumper: true, total }" @change="handleTableChange"
    >
      <template #bodyCell="{ column, text, record }">
        <template
          v-if="['department', 'mainPersonnel', 'eventName', 'eventTime', 'eventLocation', 'tags', 'link'].includes(column.dataIndex as string)"
        >
          <div>
            <a-input
              v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex as string]"
              style="margin: -0.667vw 0;"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <a-typography-link @click="save(record.id)">保存</a-typography-link>
              <a @click="cancel(record.id)">取消</a>
            </span>
            <span v-else>
              <a-space>
                <a @click="showModalImg(record)">预览</a>
                <a @click="moveFile(record)">移动文件</a>
                <a @click="edit(record.id)">编辑</a>
                <a v-if="data.length" @click="onDelete(record)">删除</a>
              </a-space>
            </span>
          </div>
        </template>
      </template>
    </a-table>
    <!-- 预览 -->
    <a-modal v-model:visible="visibleImg" footer="">
      <div v-if="isMp4(imgItem.link)">
        <video :src="imgItem.link" style="width: 100%;height: 18vw;" controls />
      </div>
      <a-image
        v-else :src="imgItem.link" :alt="imgItem.title" style="width: 100%;height: 18vw;" loading="lazy"
        :fallback="useFallBack().fallback"
      />
    </a-modal>
    <!-- 移动文件夹 -->
    <a-modal v-model:visible="visibleFile" title="移动文件夹" @ok="handleOk">
      <a-radio-group v-model:value="choose" style="margin: 1.067vw;">
        <a-radio-button value="1">
          选择
        </a-radio-button>
        <a-radio-button value="2">
          创建
        </a-radio-button>
      </a-radio-group>
      <a-select v-if="ischoose1()" v-model:value="value1" style="width: 15vw;" :options="options" />
      <a-input v-if="!ischoose1()" v-model:value="value1" style="width: 18vw;" />
    </a-modal>
  </div>
</template>

<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 3vw;
  margin-bottom: 0.5vw;

  .pjTitle {
    padding-left: 1vw;
    background: url("@/assets/images/title-left-bg.svg") no-repeat;
  }

  .right {
    display: flex;
    align-items: center;
  }
}

.editable-row-operations a {
  margin-right: 1.067vw;
}

.content {
  box-sizing: border-box;
  max-width: 100%;
  max-height: 66.667vw;
  overflow-y: auto;

  .d-table {
    padding: 0.6vw;
    overflow-y: auto;
  }
}
</style>
